package com.itts.middle.utils;

import com.itts.common.entity.User;
import lombok.SneakyThrows;
import org.junit.Test;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class sortUtil {

    /**
     *
     * @param list 排序对象
     * @param o 指定字段-- todo 实体类字段值时int类型, 重写set的方法
     * @param <T>
     * @return
     */
    public static <T> List<T> sort(List<T> list, String o) {
        Collections.sort(list, new Comparator<T>() {
            @SneakyThrows
            @Override
            public int compare(T o1, T o2) {
                Class<?> o1Class = o1.getClass();
                PropertyDescriptor pd = new PropertyDescriptor(o, o1Class);
                Method readMethod = pd.getReadMethod();
                int s1 = (int) readMethod.invoke(o1);

                Class<?> o2Class = o2.getClass();
                PropertyDescriptor pd2 = new PropertyDescriptor(o, o2Class);
                Method readMethod2 = pd2.getReadMethod();
                int s2 = (int) readMethod2.invoke(o2);
                if (s1 > s2) {
                    return -1;
                }
                if (s1 < s2) {
                    return 1;
                }
                return 0;
            }
        });
        return list;
    }

    @Test
    public void test() {
        User user = new User("aa", 123, "hhh");
        Class<? extends User> aClass1 = user.getClass();
        try {
            //获取实体类的属性
            //按照API的说法，getFields()方法只能返回声明类中被public修饰的成员字段，不能得到private，protected等修饰的成员字段
            //getDeclaredFields 暴力获取全部成员字段
            //Class<?> aClass = Class.forName("com.itts.common.entity.Project");
            Field[] fields = aClass1.getDeclaredFields();
            for (Field field : fields) {
                System.out.println("字段: " + field.getName());

                //获取字段值, 通过get属性获取
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), aClass1);
                Method readMethod = pd.getReadMethod();
                Object invoke = readMethod.invoke(user);
                System.out.println(invoke);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
